package com.tangyee.home_blood_center.view;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;

import com.tangyee.home_blood_center.utils.DensityUtils;
import com.tangyee.R;
import com.tangyee.home_blood_center.utils.DensityUtils;

import java.util.ArrayList;

/**
 * 偷来的表格View，并自己改动了几个地方
 * MPAndroidChart太高级了，用不好
 */
public class LineGraphicView extends View {

    private static final int CIRCLE_SIZE = 10;

    private static enum Linestyle {Line, Curve}

    private Context mContext;
    private Paint mPaint;
    private Resources res;
    private DisplayMetrics dm;

    // data
    private Linestyle mStyle = Linestyle.Line;
    private int canvasHeight;
    private int canvasWidth;
    private int bheight = 0;
    private int blwidh;
    private boolean isMeasure = true;

    // y轴最大值
    private int maxValue;

    // y轴间距值
    private int averageValue;
    private int marginTop = DensityUtils.dp2px(getContext(),20);
    private int marginBottom = DensityUtils.dp2px(getContext(),60);

    // 曲线上的总点数
    private Point[] mPoints;

    // 纵坐标值
    private ArrayList<Double> yRawData;

    // 横坐标值
    private ArrayList<String> xRawDatas;
    private ArrayList<Integer> xList = new ArrayList<>();/* 记录每个x的值*/
    private int spacingHeight;

    // 是否水平绘制文字
    private boolean isHorizontalDrawText;

    public LineGraphicView(Context context) {
        this(context, null);
    }

    public LineGraphicView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        initView();
    }

    private void initView() {
        this.res = mContext.getResources();
        this.mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (isMeasure) {
            this.canvasHeight = getHeight();
            this.canvasWidth = getWidth();
            if (isHorizontalDrawText)
                this.canvasWidth -= dip2px(24);
            if (bheight == 0) bheight = (int) (canvasHeight - marginBottom - marginTop);
            blwidh = dip2px(30);
            isMeasure = false;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint.setColor(res.getColor(R.color.colorLine));
        mPaint.setStrokeWidth(dip2px(0.5f));
        drawAllXLine(canvas);/* 画直线（纵向）*/
        drawAllYLine(canvas);/* 点的操作设置*/
        mPoints = getPoints();
        mPaint.setColor(res.getColor(R.color.blood_center_green));
        mPaint.setStrokeWidth(dip2px(2f));
        mPaint.setStyle(Style.STROKE);
        if (mStyle == Linestyle.Curve) drawScrollLine(canvas);
        else drawLine(canvas);
        mPaint.setStyle(Style.FILL);
        for (int i = 0; i < mPoints.length; i++)
            canvas.drawCircle(mPoints[i].x, mPoints[i].y, CIRCLE_SIZE / 2, mPaint);
    }

    /**
     * 画所有横向线条，包括X轴
     */
    private void drawAllXLine(Canvas canvas) {
        for (int i = 0; i < spacingHeight + 1; i++) {
            if (yRawData.size() > 10){
                canvas.drawLine(blwidh, bheight - (bheight / spacingHeight) * i + marginTop, blwidh + (canvasWidth - blwidh) / yRawData.size() * (yRawData.size() - 1), bheight - (bheight / spacingHeight) * i + marginTop, mPaint);/* Y坐标*/
            } else {
                canvas.drawLine(blwidh, bheight - (bheight / spacingHeight) * i + marginTop, canvasWidth, bheight - (bheight / spacingHeight) * i + marginTop, mPaint);/* Y坐标*/
            }
            drawText(String.valueOf(averageValue * i), blwidh / 3, bheight - (bheight / spacingHeight) * i + marginTop, canvas);
        }
    }

    /**
     * 画所有纵向线条，包括Y轴
     */
    private void drawAllYLine(Canvas canvas) {
        for (int i = 0; i < yRawData.size(); i++) {
            if (!isHorizontalDrawText) { // 不是水平绘制文字
                xList.add(blwidh + (canvasWidth - blwidh) / yRawData.size() * i);
                canvas.drawLine(blwidh + (canvasWidth - blwidh) / yRawData.size() * i, marginTop, blwidh + (canvasWidth - blwidh) / yRawData.size() * i, bheight + marginTop, mPaint);
                canvas.rotate((float) (45), blwidh + (canvasWidth - blwidh) / yRawData.size() * i, bheight + dip2px(26));
                if (yRawData.size() > 10) {
                    if (i % 5 == 0)
                        drawText(xRawDatas.get(i), blwidh + (canvasWidth - blwidh) / yRawData.size() * i, bheight + dip2px(26), canvas);/* X坐标*/
                } else {
                    drawText(xRawDatas.get(i), blwidh + (canvasWidth - blwidh) / yRawData.size() * i, bheight + dip2px(26), canvas);/* X坐标*/
                }
                canvas.rotate(-(float) (45), blwidh + (canvasWidth - blwidh) / yRawData.size() * i, bheight + dip2px(26));
            } else { // 是水平居中绘制文字
                // 画纵向线条
                xList.add(blwidh + (canvasWidth - blwidh) / (yRawData.size() - 1) * i);
                canvas.drawLine(blwidh + (canvasWidth - blwidh) / (yRawData.size() - 1) * i, marginTop, blwidh + (canvasWidth - blwidh) /  (yRawData.size() - 1)  * i, bheight + marginTop, mPaint);
                // 画x轴文字
                double n = 2.5;
                if (xRawDatas.get(i).length() == 2)
                    n = 2;
                if (xRawDatas.get(i).length() == 3)
                    n = 3;
                if (yRawData.size() > 10) {
                    if (i % 5 == 0)
                        drawText(xRawDatas.get(i), blwidh + (canvasWidth - blwidh) / (yRawData.size() - 1) * i - (int)(dip2px(12) * n / 2), (int)(bheight + dip2px(26) * 1.5), canvas);/* X坐标*/
                } else {
                    drawText(xRawDatas.get(i), blwidh + (canvasWidth - blwidh) / (yRawData.size() - 1) * i - (int)(dip2px(12) * n / 2), (int)(bheight + dip2px(26) * 1.5), canvas);/* X坐标*/
                }
            }
        }
    }

    private void drawVerticalText(String s, Canvas canvas, int x, int y) {
        int length = s.length();
        for (int i = 0; i < length; i ++) {
            drawText(String.valueOf(s.charAt(i)), x, y + i * dip2px(13), canvas);
        }
    }

    private void drawScrollLine(Canvas canvas) {
        Point startp = new Point();
        Point endp = new Point();
        for (int i = 0; i < mPoints.length - 1; i++) {
            startp = mPoints[i];
            endp = mPoints[i + 1];
            int wt = (startp.x + endp.x) / 2;
            Point p3 = new Point();
            Point p4 = new Point();
            p3.y = startp.y;
            p3.x = wt;
            p4.y = endp.y;
            p4.x = wt;
            Path path = new Path();
            path.moveTo(startp.x, startp.y);
            path.cubicTo(p3.x, p3.y, p4.x, p4.y, endp.x, endp.y);
            canvas.drawPath(path, mPaint);
        }
    }

    private void drawLine(Canvas canvas) {
        Point startp = new Point();
        Point endp = new Point();
        for (int i = 0; i < mPoints.length - 1; i++) {
            startp = mPoints[i];
            endp = mPoints[i + 1];
            canvas.drawLine(startp.x, startp.y, endp.x, endp.y, mPaint);
        }
    }

    private void drawText(String text, int x, int y, Canvas canvas) {
        Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
        p.setTextSize(dip2px(12));
        p.setColor(res.getColor(R.color.colorLine));
        p.setTextAlign(Paint.Align.LEFT);
        canvas.drawText(text, x, y, p);
    }

    private Point[] getPoints() {
        Point[] points = new Point[yRawData.size()];
        for (int i = 0; i < yRawData.size(); i++) {
            int ph = bheight - (int) (bheight * (yRawData.get(i) / maxValue));
            points[i] = new Point(xList.get(i), ph + marginTop);
        }
        return points;
    }

    public void setData(ArrayList<Double> yRawData, ArrayList<String> xRawData, int maxValue, int averageValue) {
        this.maxValue = maxValue;
        this.averageValue = averageValue;
        this.mPoints = new Point[yRawData.size()];
        this.xRawDatas = xRawData;
        this.yRawData = yRawData;
        this.spacingHeight = maxValue / averageValue;
        Log.d("spacingHeight", "setData: " + spacingHeight);
    }

    public void setTotalvalue(int maxValue) {
        this.maxValue = maxValue;
    }

    public void setPjvalue(int averageValue) {
        this.averageValue = averageValue;
    }

    public void setMargint(int marginTop) {
        this.marginTop = marginTop;
    }

    public void setMarginb(int marginBottom) {
        this.marginBottom = marginBottom;
    }

    public void setMstyle(Linestyle mStyle) {
        this.mStyle = mStyle;
    }

    public void setBheight(int bheight) {
        this.bheight = bheight;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dip2px(float dpValue) {
        return (int) (dpValue * dm.density + 0.5f);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void setHorizontalDrawText(boolean b) {
        this.isHorizontalDrawText = b;
    }

}